<?php
/**
 * Mysql会话管理器
 *
 */
class session 
{
	private $lifetime;//会话存在的时间
	
	private $pdo;
	
	public function __construct() {
		if(file_exists(BASEPATH.'db/dbBase'.EXT)) {
			require_once(BASEPATH.'db/dbBase'.EXT);
			$this->pdo = dbBase::getInstance()->get();		
		}
		date_default_timezone_set('Asia/Shanghai');
		session_module_name('user');
		session_set_save_handler(array(&$this, 'open'),
                                array(&$this, 'close'),
                                array(&$this, 'read'),
                                array(&$this,'write'),                  
                                array(&$this, 'destroy'),
                                array(&$this, 'garbageCollect')
                                );
        
		session_start();
	}
	
	public function open($session_path,$session_name) {
		
		return true;
	}
	
	public function close() {
		return true;
	}
	
	protected function read($session_id) {
		$session_id = $this->pdo->quote($session_id);
		$query = "SELECT session_value FROM beauty_session WHERE session_id = $session_id AND session_expire >".time();
		$stmt = $this->pdo->prepare($query);
		$stmt->execute();
		
		if($stmt->rowCount() > 0){
			$row = $stmt->fetch(PDO::FETCH_OBJ);
			return $row->session_value;
		} else {
			return '';
		}
	}
	
	public function write($session_id,$session_value) {
		$this->lifetime = get_cfg_var("session.gc_maxlifetime");
		$session_expire = time() + $this->lifetime;
		$query = "SELECT session_id FROM beauty_session WHERE session_id = '$session_id'";
		$stmt = $this->pdo->prepare($query);
		$stmt->execute();
		
		if($stmt->rowCount() > 0) {
		$sql = "UPDATE beauty_session SET session_expire = '$session_expire',session_value = '$session_value' WHERE session_id = '$session_id' AND session_expire>".time();
			$this->pdo->exec($sql);
		} else {
			$sql = "INSERT INTO beauty_session(session_id,session_value,session_expire) VALUES('$session_id','$session_value','$session_expire') ";
			$this->pdo->exec($sql);
		}

	}
	
	public function destroy($session_id) {
		$sql = "DELETE FROM beauty_session WHERE session_id = '$session_id'";
		$this->pdo->exec($sql);
	}
	
	public function garbageCollect() {
		//$sql = "DELETE FROM beauty_session WHRER session_expire < ".time() - $this->lifetime;
		$sql = "DELETE FROM beauty_session WHRER session_expire < ".time() - get_cfg_var("session.gc_maxlifetime");
		$this->pdo->exec($sql);
	}
	
	public function get($item) {
		return isset($_SESSION[$item]) ? $_SESSION[$item] : null;
	}
 	
	public function set($key,$value) {
		$_SESSION[$key] = stripslashes($value);
 	}
	
 	public function logout() {
 		session_destroy();
 	}
}
?>